<template>
  <el-form>
    <el-form-item label="选择竞赛">
      <el-select
        v-model="selectedContestId"
        placeholder="请选择竞赛"
        @change="onChange"
        :loading="loading"
      >
        <el-option
          v-for="contest in contests"
          :key="contest.contestId"
          :label="`${contest.title}（${contest.startTime}~${contest.endTime}）`"
          :value="contest.contestId"
        />
      </el-select>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, watch, defineProps, defineEmits } from 'vue'
import axios from 'axios'

const props = defineProps({
  modelValue: String, // v-model 支持
  contests: Array, // 可选，外部传入竞赛列表
  role: String // 可选，角色参数，便于扩展
})
const emit = defineEmits(['update:modelValue', 'change', 'loaded'])

const contests = ref(props.contests || [])
const loading = ref(false)
const selectedContestId = ref(props.modelValue || '')

const fetchContests = async () => {
  if (props.contests && props.contests.length > 0) {
    contests.value = props.contests
    emit('loaded', contests.value)
    return
  }
  loading.value = true
  try {
    const token = localStorage.getItem('token')
    const res = await axios.get('/api/contests', {
      headers: { 'Authorization': `Bearer ${token}` }
    })
    if (res.data.code === 200) {
      contests.value = res.data.data
      emit('loaded', contests.value)
    } else {
      contests.value = []
    }
  } catch (e) {
    contests.value = []
  } finally {
    loading.value = false
  }
}

watch(() => props.contests, (val) => {
  if (val && val.length > 0) {
    contests.value = val
  } else {
    fetchContests()
  }
}, { immediate: true })

watch(() => props.modelValue, (val) => {
  selectedContestId.value = val
})

const onChange = (val) => {
  emit('update:modelValue', val)
  emit('change', contests.value.find(c => c.contestId === val))
}
</script>
